package cn.itcast.util;

import org.apache.commons.io.IOUtils;

import java.awt.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TextUtils {
    public static boolean isEmpty(CharSequence str) {
        if (str == null || str.length() == 0)
            return true;
        else
            return false;
    }
    public static boolean equals(CharSequence a, CharSequence b) {
        if (a == b) return true;
        int length;
        if (a != null && b != null && (length = a.length()) == b.length()) {
            if (a instanceof String && b instanceof String) {
                return a.equals(b);
            } else {
                for (int i = 0; i < length; i++) {
                    if (a.charAt(i) != b.charAt(i)) return false;
                }
                return true;
            }
        }
        return false;
    }

    /**
     * 只要str其中一个包含 main 就返回true
     * @param main
     * @param str
     * @return
     */
    public static boolean equals(CharSequence main,String... str){
        if(main==null)return false;
        if(str==null)return false;
        for(String s:str){
            if(equals(main,s))
                return true;
        }
        return false;
    }

    public static String randomUUID(){
        return randomUUID(true);
    }
    /**
     * 生成订单id 格式如 前8位 为年月日 后12位随机数
     * @return
     */
    public static String randomTid(){
        String dateStr=  DateUtils.format("yyyyMMddHHmmss");
        int hashId= TextUtils.randomUUID().hashCode();
        if(hashId<0){
            hashId= -hashId;
        }
        String r=hashId+"";
        r=r.substring(0,r.length()-4);
        return dateStr+String.format("%06d", Integer.parseInt(r));
    }
    public static String randomUUID(boolean l){
        if(l) return UUID.randomUUID().toString().replace("-", "");
        return UUID.randomUUID().toString();
    }

    public static Long[] toStrings(String[] s){
        if(s==null) return null;
        Long[] longs=new Long[s.length];
        for (int i = 0; i < s.length; i++) {
            try {
                longs[i] = Long.parseLong(s[i]);
            }catch (Exception e){longs[i]=null;}
        }
        return longs;
    }

    public static String toString(Long[] ids){
       return longs2String(ids);
    }
    public static String longs2String(Long[] ids){
        if(ids==null)return null;
        StringBuffer stringBuffer=new StringBuffer();
        for(Long id:ids){
            stringBuffer.append(id).append(",");
        }
        return stringBuffer.substring(0,stringBuffer.length()-1);
    }

    public static Color toRgb(String f){
        Color color = Color.BLACK;
        try {
            if (f.startsWith("#") & f.length() == 7 || f.startsWith("#") & f.length() == 9) {
                int length = f.length();
                int size = 3;
                if (length > 7) size = 4;
                int[] ints = new int[size];
                int next = 0;
                for (int i = 1; i < length; i += 2) {
                    String hex = f.substring(i, i + 2);
                    ints[next] = Integer.parseInt(hex, 16);
                    next++;
                }
                if (ints.length > 3) color = new Color(ints[0], ints[1], ints[2], ints[3]);
                else color = new Color(ints[0], ints[1], ints[2]);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return color;
    }

    public static String fileToString(String path){
        try {
            InputStreamReader in = new InputStreamReader(new FileInputStream(path), "Utf8");
            return toString(in);
        }catch (Exception e){
            return null;
        }
    }

    public static String toString(InputStream inputStream){
        try {
            return  IOUtils.toString(inputStream,"utf8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Long toLong(Object object){
        try {
            if (object instanceof Long)
                return (Long) object;
            else if (object instanceof BigInteger) {
                BigInteger integer = (BigInteger) object;
                return integer.longValue();
            } else if (object instanceof Integer) {
                return Long.valueOf(((Integer) object));
            } else if (object instanceof String) {
                return Long.parseLong(object.toString());
            } else {
                return (Long) object;
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }



    public static String toString(Object object){
        if(object==null)return null;
        return object.toString();
    }

    public static Float toFloat(Object object){
        if(object==null)return 0f;
        try{
            if(object instanceof Long)
                return ((Long) object).floatValue();
            else if(object instanceof Integer)
                return ((Integer) object).floatValue();
            else if(object instanceof BigDecimal)
                return ((BigDecimal) object).floatValue();
            else if(object instanceof BigInteger)
                return ((BigInteger) object).floatValue();
            else if(object instanceof Double) return ((Double) object).floatValue();
            else return Float.parseFloat(object.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0f;
    }

    public static int random(int min,int max){
        int random= 1+(int)(Math.random()*50);
        return random;
    }
    public  static int random(int max){
        return random(0,max);
    }

    public static String randomStr(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        int maxPos = chars.length();
        String pwd = "";
        for (int i = 0; i < length; i++) {
            char c = chars.charAt((int) Math.floor(Math.random() * maxPos));
            pwd += String.valueOf(c);
        }
        return pwd;
    }


    public static void main(String[] ages) throws UnsupportedEncodingException {
        String[] strs="bbb".split("/");

      System.out.println(strs[strs.length-1]);
    }

    public static boolean isPhone(String phone) {
        if(!TextUtils.isEmpty(phone)&&phone.trim().length()==11) {
            String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone.trim());
            boolean isMatch = m.matches();
            return isMatch;
        }else return false;
    }

    public static String toFixed(Float money) {
        if(money==null)money=0f;
        DecimalFormat df=new DecimalFormat("#.##");
        return df.format(money);
    }

    public static String hideName(String fullName) {
        if(isEmpty(fullName))return "**";
        String realname=fullName.substring(0,1);
        return realname+"**";
    }

    /**
     * sql 关键字过滤
     */
    private static String[] sql_str  = ("' |insert |select |drop |master |truncate |" +
            "declare |net user |xp_cmdshell |or |like' |and |execute |insert |" +
            "table |grant |use |group_concat |column_name |" +
            "information_schema.columns |table_schema |union |by |" +
            "truncate |char |declare |like "+
            " '| insert| select| drop| master| truncate|"+
            " declare| netuser| xp_cmdshell| or| like'| and| execute| insert|"+
            " table| grant| use| group_concat| column_name|"+
            " information_schema.columns| table_schema| union| by|"+
            " truncate| char| declare| like").split("\\|");

    /**
     * sql 关键字过滤
     */
    public static String sqlValid(String type) {
        if(TextUtils.isEmpty(type))return type;
        for (String str:sql_str ) {
            type=type.replaceAll(str.toLowerCase(),"");
            type=type.replaceAll(str.toUpperCase(),"");
        }
        return type.trim();
    }

    public static Object hideNick(String nickname) {
        if(TextUtils.isEmpty(nickname))return "**";
        if(nickname.length()<=1)return nickname+"**";
        int l=nickname.length()/2;
        nickname=nickname.substring(0,l)+"**";

        return nickname;
    }

    public static boolean contain(CharSequence str,String contain) {
        if(str==null)return false;
        if(str.toString().indexOf(contain)>-1)return true;
        else return false;
    }

}
